package practice.lucene.part02;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import practice.common.Constant;

import javax.naming.Name;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 12-4-23
 * Time: 上午12:03
 * 索引内存或者网页中的数据
 */
public class LuceneText {

    //模拟一组数据

    private String[] ids = {"1", "2", "3", "4"};

    private String[] emails = {"aa@beka.com", "bb@beka.com", "cc@beka.com", "dd@163.com"};

    private String[] content = {
            "this is first mail",
            "hello two mail",
            "i like here",
            "good job"
    };

    private int[] status = {2, 3, 4, 5};

    private Date[] dates = null;

    private String[] name = {"jokey", "lily", "tomy", "zhangshan"};

    private Directory directory = null;

    //创建文档
    public LuceneText() {
        //指定索引存放的目录
        try {
            directory = FSDirectory.open(new File(Constant.lucencePath));
            setDate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setDate() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            dates = new Date[content.length];
            dates[0] = sdf.parse("2012-04-24");
            dates[1] = sdf.parse("2012-04-22");
            dates[2] = sdf.parse("2012-04-21");
            dates[3] = sdf.parse("2012-04-26");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建文档
     */
    public void createIndex() {
        IndexWriter writer = null;
        try {
            IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
            writer = new IndexWriter(directory, conf);
            writer.deleteAll();//清空索引
            Document doc = null;
            for (int i = 0; i < ids.length; i++) {
                doc = new Document();
                doc.add(new Field("id", ids[i], Field.Store.YES, Field.Index.ANALYZED));
                doc.add(new Field("email", emails[i], Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("content", content[i], Field.Store.NO, Field.Index.ANALYZED));
                doc.add(new Field("name", name[i], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
                //数字加索引
                doc.add(new NumericField("status", Field.Store.YES, true).setIntValue(status[i]));
                 //日期索引
                doc.add(new NumericField("date", Field.Store.YES, true).setLongValue(dates[i].getTime()));

                 writer.addDocument(doc);
            }
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 使用   IndexWriter 来完成删除操作
     */
    public void deleteIndex() throws Exception {
        IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
        IndexWriter writer = new IndexWriter(directory, conf);
        //query：一组查询结果
        //term精确查询的结果
        //删除后可会恢复：
        //numdocs：本来6个 删掉后是5
        //maxdocs：6，会显示已经删除的数据
        writer.deleteDocuments(new Term("id", "1")); //删除掉id为1的所有元素
    }

    /**
     * 使用   IndexReader 来完成删除操作
     */
    public void undeleteIndex() throws Exception {
        IndexReader reader = IndexReader.open(directory);
        // 将在lucene4.0.中取消
        reader.undeleteAll();
        reader.close();
    }

    /**
     * 更新索引
     *
     * @throws Exception
     */
    public void updateIndex() throws Exception {
        //
        IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
        IndexWriter writer = new IndexWriter(directory, conf);
        writer.deleteAll();//清空索引
        Document doc = null;
        for (int i = 0; i < ids.length; i++) {
            doc = new Document();
            doc.add(new Field("id", ids[i], Field.Store.YES, Field.Index.ANALYZED));
            doc.add(new Field("email", emails[i], Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.add(new Field("content", content[i], Field.Store.NO, Field.Index.ANALYZED));
            doc.add(new Field("name", name[i], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
            writer.addDocument(doc);
        }
        //先删除后更新 ：删除为1的doc，后添加一个对象doc
        writer.updateDocument(new Term("id", "1"), doc);
        writer.close();
    }


    /**
     * 查询索引 *
     */
    public void searcher(String queryString) {
        try {
            //创建indexReader读取索引
            IndexReader reader = IndexReader.open(directory);
            //显示存储的文档数目：
            System.out.println("文档数目:" + reader.numDocs());
            System.out.println("maxDoc:" + reader.maxDoc());
            IndexSearcher searcher = new IndexSearcher(reader);
            TermQuery query = new TermQuery(new Term("content", "mail"));
            TopDocs docs = searcher.search(query, 10);
            for (ScoreDoc doc : docs.scoreDocs) {
                Document docu = searcher.doc(doc.doc);
                System.out.println(docu.get("name") + "[" + docu.get("pathname") + "]");
            }
            //根据indexReader创建indexSeacher
//            IndexSearcher searcher = reader.ge
            //创建搜索的query
            //根据searcher搜索并且返回topDocs
            //根据TopDocs回去ScoreDoc对象
            //根据searcher和ScoreDoc对象获取具体的document对象
            //由Document对象获取需要的值
            //关闭indexReader
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
